class SnakeGame {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.scoreElement = document.getElementById('score');
        this.highScoreElement = document.getElementById('highScore');
        this.finalScoreElement = document.getElementById('finalScore');
        this.gameOverModal = document.getElementById('gameOverModal');
        
        this.gridSize = 20;
        this.tileCount = this.canvas.width / this.gridSize;
        
        this.resetGame();
        this.bindEvents();
        this.loadHighScore();
    }
    
    resetGame() {
        this.snake = [
            {x: 10, y: 10}
        ];
        this.dx = 0;
        this.dy = 0;
        this.food = this.generateFood();
        this.score = 0;
        this.gameRunning = false;
        this.gamePaused = false;
        
        this.updateScore();
    }
    
    generateFood() {
        return {
            x: Math.floor(Math.random() * this.tileCount),
            y: Math.floor(Math.random() * this.tileCount)
        };
    }
    
    bindEvents() {
        document.addEventListener('keydown', (e) => this.handleKeyPress(e));
        document.getElementById('startBtn').addEventListener('click', () => this.startGame());
        document.getElementById('pauseBtn').addEventListener('click', () => this.togglePause());
        document.getElementById('restartBtn').addEventListener('click', () => this.restartGame());
        document.getElementById('playAgainBtn').addEventListener('click', () => this.restartGame());
    }
    
    handleKeyPress(e) {
        if (!this.gameRunning || this.gamePaused) return;
        
        const goingUp = this.dy === -1;
        const goingDown = this.dy === 1;
        const goingRight = this.dx === 1;
        const goingLeft = this.dx === -1;
        
        switch(e.key) {
            case 'ArrowLeft':
                if (!goingRight) {
                    this.dx = -1;
                    this.dy = 0;
                }
                break;
            case 'ArrowUp':
                if (!goingDown) {
                    this.dx = 0;
                    this.dy = -1;
                }
                break;
            case 'ArrowRight':
                if (!goingLeft) {
                    this.dx = 1;
                    this.dy = 0;
                }
                break;
            case 'ArrowDown':
                if (!goingUp) {
                    this.dx = 0;
                    this.dy = 1;
                }
                break;
        }
    }
    
    startGame() {
        if (this.gameRunning) return;
        
        this.gameRunning = true;
        this.gamePaused = false;
        this.dx = 1;
        this.dy = 0;
        
        document.getElementById('startBtn').style.display = 'none';
        document.getElementById('pauseBtn').style.display = 'inline-block';
        document.getElementById('restartBtn').style.display = 'inline-block';
        
        this.gameLoop();
    }
    
    togglePause() {
        if (!this.gameRunning) return;
        
        this.gamePaused = !this.gamePaused;
        document.getElementById('pauseBtn').textContent = this.gamePaused ? '继续' : '暂停';
        
        if (!this.gamePaused) {
            this.gameLoop();
        }
    }
    
    restartGame() {
        this.resetGame();
        this.gameOverModal.style.display = 'none';
        document.getElementById('startBtn').style.display = 'inline-block';
        document.getElementById('pauseBtn').style.display = 'none';
        document.getElementById('restartBtn').style.display = 'none';
        this.draw();
    }
    
    gameLoop() {
        if (!this.gameRunning || this.gamePaused) return;
        
        this.update();
        this.draw();
        
        setTimeout(() => this.gameLoop(), 100);
    }
    
    update() {
        const head = {x: this.snake[0].x + this.dx, y: this.snake[0].y + this.dy};
        
        // 检查撞墙
        if (head.x < 0 || head.x >= this.tileCount || 
            head.y < 0 || head.y >= this.tileCount) {
            this.gameOver();
            return;
        }
        
        // 检查撞到自己
        for (let segment of this.snake) {
            if (head.x === segment.x && head.y === segment.y) {
                this.gameOver();
                return;
            }
        }
        
        this.snake.unshift(head);
        
        // 检查吃到食物
        if (head.x === this.food.x && head.y === this.food.y) {
            this.score += 10;
            this.updateScore();
            this.food = this.generateFood();
            
            // 检查是否获胜
            if (this.score >= 1000) {
                this.gameOver(true);
                return;
            }
        } else {
            this.snake.pop();
        }
    }
    
    draw() {
        // 清空画布
        this.ctx.fillStyle = '#f0f0f0';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制蛇
        this.ctx.fillStyle = '#667eea';
        for (let i = 0; i < this.snake.length; i++) {
            this.ctx.fillRect(
                this.snake[i].x * this.gridSize, 
                this.snake[i].y * this.gridSize, 
                this.gridSize - 2, 
                this.gridSize - 2
            );
            
            // 蛇头特殊颜色
            if (i === 0) {
                this.ctx.fillStyle = '#764ba2';
                this.ctx.fillRect(
                    this.snake[i].x * this.gridSize + 2, 
                    this.snake[i].y * this.gridSize + 2, 
                    this.gridSize - 6, 
                    this.gridSize - 6
                );
            }
        }
        
        // 绘制食物
        this.ctx.fillStyle = '#ff6b6b';
        this.ctx.fillRect(
            this.food.x * this.gridSize, 
            this.food.y * this.gridSize, 
            this.gridSize - 2, 
            this.gridSize - 2
        );
        
        // 食物高光效果
        this.ctx.fillStyle = '#ff8787';
        this.ctx.fillRect(
            this.food.x * this.gridSize + 4, 
            this.food.y * this.gridSize + 4, 
            this.gridSize - 10, 
            this.gridSize - 10
        );
    }
    
    updateScore() {
        this.scoreElement.textContent = this.score;
        if (this.score > this.getHighScore()) {
            this.setHighScore(this.score);
            this.highScoreElement.textContent = this.score;
        }
    }
    
    gameOver(won = false) {
        this.gameRunning = false;
        this.finalScoreElement.textContent = this.score;
        this.gameOverModal.style.display = 'flex';
        
        if (won) {
            document.querySelector('.modal-content h2').textContent = '恭喜通关!';
        } else {
            document.querySelector('.modal-content h2').textContent = '游戏结束!';
        }
    }
    
    loadHighScore() {
        const highScore = localStorage.getItem('snakeHighScore') || 0;
        this.highScoreElement.textContent = highScore;
    }
    
    getHighScore() {
        return parseInt(localStorage.getItem('snakeHighScore') || 0);
    }
    
    setHighScore(score) {
        localStorage.setItem('snakeHighScore', score);
    }
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    const game = new SnakeGame();
    game.draw();
});
